<template>
  <div class="app-container">
    <!-- 筛选条件区域 -->
    <el-form :model="queryParams" ref="queryForm" size="small" label-width="100px" class="mb10" v-show="showSearch">
      <el-row :gutter="10">
        <el-col :span="6">
          <el-form-item label="看板编号" prop="kanbanCode">
            <el-input v-model="queryParams.kanbanCode" clearable placeholder="请输入看板编号"
              @keyup.enter.native="handleQuery" @clear="handleQuery" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="协议编号" prop="frameworkCode">
            <el-input v-model="queryParams.frameworkCode" clearable placeholder="请输入协议编号"
              @keyup.enter.native="handleQuery" @clear="handleQuery" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="要货公司" prop="receiverCompanyName">
            <el-input v-model="queryParams.receiverCompanyName" clearable placeholder="请输入要货公司名称"
              @keyup.enter.native="handleQuery" @clear="handleQuery" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="发货公司" prop="senderCompanyName">
            <el-input v-model="queryParams.senderCompanyName" clearable placeholder="请输入发货公司名称"
              @keyup.enter.native="handleQuery" @clear="handleQuery" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span="6">
          <el-form-item label="物料编码" prop="materialCode">
            <el-input v-model="queryParams.materialCode" clearable placeholder="请输入物料编码"
              @keyup.enter.native="handleQuery" @clear="handleQuery" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="物料名称" prop="materialName">
            <el-input v-model="queryParams.materialName" clearable placeholder="请输入物料名称"
              @keyup.enter.native="handleQuery" @clear="handleQuery" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="业务状态" prop="businessStatus">
            <el-select v-model="queryParams.businessStatus" clearable placeholder="请选择业务状态" @change="handleQuery"
              @clear="handleQuery">
              <el-option v-for="dict in dict.type.yaohuokb_business" :key="dict.value" :label="dict.label"
                :value="dict.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="确认状态" prop="senderConfirmStatus">
            <el-select v-model="queryParams.senderConfirmStatus" clearable placeholder="请选择确认状态" @change="handleQuery"
              @clear="handleQuery">
              <el-option label="未确认" value="0" />
              <el-option label="已确认" value="1" />
              <el-option label="已拒绝" value="2" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item label="创建时间" prop="createTimeRange">
            <el-date-picker
              v-model="queryParams.createTimeRange"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="yyyy-MM-dd HH:mm:ss"
              value-format="yyyy-MM-dd HH:mm:ss"
              clearable
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="要求到货时间" prop="deliveryTimeRange">
            <el-date-picker
              v-model="queryParams.deliveryTimeRange"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="yyyy-MM-dd HH:mm:ss"
              value-format="yyyy-MM-dd HH:mm:ss"
              clearable
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span="24" class="text-right">
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-col>
      </el-row>
    </el-form>

    <!-- 工具栏区域 -->
    <el-row :gutter="10" class="mb10">
      <el-col :span="12">
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['kanban:order:add']">新建看板</el-button>
        <el-button type="success" icon="el-icon-refresh" size="mini" @click="getList">刷新数据</el-button>
        <el-button type="warning" icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['kanban:order:export']">导出</el-button>
      </el-col>
      <el-col :span="12" class="text-right">
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" />
      </el-col>
    </el-row>

    <!-- 数据列表区域 -->
    <el-table v-loading="loading" :data="list" border>
      <el-table-column label="看板编号" prop="kanbanCode" min-width="120" fixed="left">
        <template slot-scope="scope">
          <el-link type="primary" @click="handleView(scope.row)">{{ scope.row.kanbanCode }}</el-link>
        </template>
      </el-table-column>
      <el-table-column label="协议编号" prop="frameworkCode" min-width="120">
        <template slot-scope="scope">
          <el-link type="info" @click="viewFramework(scope.row.frameworkId)">{{ scope.row.frameworkCode }}</el-link>
        </template>
      </el-table-column>
      <el-table-column label="要货公司" prop="receiverCompanyName" min-width="150" />
      <el-table-column label="发货公司" prop="senderCompanyName" min-width="150" />
      <el-table-column label="物料编码" prop="materialCode" min-width="120" />
      <el-table-column label="物料名称" prop="materialName" min-width="180" show-overflow-tooltip />
      <el-table-column label="要货数量" prop="requiredQty" width="100" align="right">
        <template slot-scope="scope">
          {{ scope.row.requiredQty }} {{ scope.row.materialUnit }}
        </template>
      </el-table-column>
      <el-table-column label="要求到货时间" prop="requiredDeliveryTime" width="150" />
      <el-table-column label="业务状态" prop="businessStatus" width="100">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.yaohuokb_business" :value="scope.row.businessStatus" />
        </template>
      </el-table-column>
      <el-table-column label="确认状态" prop="senderConfirmStatus" width="100">
        <template slot-scope="scope">
          <el-tag :type="scope.row.senderConfirmStatus === 1 ? 'success' : scope.row.senderConfirmStatus === 2 ? 'danger' : 'info'">
            {{ scope.row.senderConfirmStatus === 1 ? '已确认' : scope.row.senderConfirmStatus === 2 ? '已拒绝' : '未确认' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建人" prop="createBy" width="100" />
      <el-table-column label="创建时间" prop="createTime" width="150" />
      <el-table-column label="操作" fixed="right" width="280">
        <template slot-scope="scope">
          <el-button type="text" size="mini" icon="el-icon-view" @click="handleView(scope.row)">
            查看</el-button>
          <el-button type="text" size="mini" icon="el-icon-edit" @click="handleEdit(scope.row)"
            v-if="scope.row.businessStatus === 10" v-hasPermi="['kanban:order:edit']">编辑</el-button>
          <el-button type="text" size="mini" icon="el-icon-circle-check" @click="handleConfirm(scope.row)"
            v-if="scope.row.businessStatus === 20 && scope.row.senderConfirmStatus === 0"
            v-hasPermi="['kanban:order:confirm']">确认</el-button>
          <el-button type="text" size="mini" icon="el-icon-printer" @click="handlePrint(scope.row)"
            v-if="scope.row.businessStatus >= 30" v-hasPermi="['kanban:order:print']">打印</el-button>
          <el-button type="text" size="mini" icon="el-icon-close" @click="handleVoid(scope.row)"
            v-if="scope.row.businessStatus < 40" v-hasPermi="['kanban:order:edit']">作废</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 确认对话框 -->
    <el-dialog title="确认看板订单" :visible.sync="confirmDialogVisible" width="500px" append-to-body>
      <el-form :model="confirmForm" label-width="100px">
        <el-form-item label="看板编号">
          <el-input v-model="confirmForm.kanbanCode" readonly />
        </el-form-item>
        <el-form-item label="确认备注">
          <el-input v-model="confirmForm.confirmRemark" type="textarea" :rows="3" placeholder="请输入确认备注（可选）" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="confirmDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitConfirm" :loading="confirmLoading">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 打印选择对话框 -->
    <el-dialog title="选择打印类型" :visible.sync="printDialogVisible" width="400px" append-to-body>
      <div class="print-options">
        <el-button type="primary" icon="el-icon-printer" @click="doPrint('kanban')" :loading="printLoading">
          打印看板
        </el-button>
        <el-button type="success" icon="el-icon-printer" @click="doPrint('boxLabel')" :loading="printLoading">
          打印箱标
        </el-button>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="printDialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 查看订单抽屉 -->
    <el-drawer
      title="查看订单详情"
      :visible.sync="viewDrawerVisible"
      direction="rtl"
      size="60%"
      :before-close="handleViewDrawerClose"
      :close-on-click-modal="false"
    >
      <div class="drawer-content" v-loading="viewLoading">
        <!-- 订单状态进度条 -->
        <el-card class="status-progress-card" shadow="never">
          <div slot="header" class="section-header">
            <i class="el-icon-s-flag"></i>
            <span>订单状态进度</span>
            <el-tag class="status-tag" :type="getStatusTagType(viewData.businessStatus)">
              {{ getStatusLabel(viewData.businessStatus) }}
            </el-tag>
          </div>
          <el-steps :active="getStatusStep(viewData.businessStatus)" finish-status="success" align-center>
            <el-step title="草稿" description="订单创建"></el-step>
            <el-step title="已创建" description="等待确认"></el-step>
            <el-step title="已确认" description="准备发货"></el-step>
            <el-step title="已发货" description="运输中"></el-step>
            <el-step title="部分收货" description="部分到达"></el-step>
            <el-step title="全部收货" description="订单完成"></el-step>
          </el-steps>
        </el-card>

        <!-- 基础信息 -->
        <el-card class="info-card" shadow="never">
          <div slot="header" class="section-header">
            <i class="el-icon-info"></i>
            <span>基础信息</span>
          </div>
          <el-row :gutter="20">
            <el-col :span="12">
              <div class="info-item">
                <label>看板编号：</label>
                <span>{{ viewData.kanbanCode || '-' }}</span>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="info-item">
                <label>协议编号：</label>
                <span>{{ viewData.frameworkCode || '-' }}</span>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="info-item">
                <label>要货公司：</label>
                <span>{{ viewData.receiverCompanyName || '-' }}</span>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="info-item">
                <label>发货公司：</label>
                <span>{{ viewData.senderCompanyName || '-' }}</span>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="info-item">
                <label>收货部门：</label>
                <span>{{ viewData.receiverDeptName || '-' }}</span>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="info-item">
                <label>发货部门：</label>
                <span>{{ viewData.senderDeptName || '-' }}</span>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="info-item">
                <label>收货仓库：</label>
                <span>{{ viewData.receiverWarehouseName || '-' }}</span>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="info-item">
                <label>发货仓库：</label>
                <span>{{ viewData.senderWarehouseName || '-' }}</span>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="info-item">
                <label>收货联系人：</label>
                <span>{{ viewData.receiverContact || '-' }}</span>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="info-item">
                <label>收货电话：</label>
                <span>{{ viewData.receiverPhone || '-' }}</span>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="info-item">
                <label>发货联系人：</label>
                <span>{{ viewData.senderContact || '-' }}</span>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="info-item">
                <label>发货电话：</label>
                <span>{{ viewData.senderPhone || '-' }}</span>
              </div>
            </el-col>
          </el-row>
        </el-card>

        <!-- 物料信息 -->
        <el-card class="material-card" shadow="never">
          <div slot="header" class="section-header">
            <i class="el-icon-goods"></i>
            <span>物料信息</span>
          </div>
          <el-row :gutter="20">
            <el-col :span="12">
              <div class="info-item">
                <label>物料编码：</label>
                <span>{{ viewData.materialCode || '-' }}</span>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="info-item">
                <label>物料名称：</label>
                <span>{{ viewData.materialName || '-' }}</span>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="info-item">
                <label>物料单位：</label>
                <span>{{ viewData.materialUnit || '-' }}</span>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="info-item">
                <label>包装类型：</label>
                <span>{{ viewData.packageType || '-' }}</span>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="info-item">
                <label>要货数量：</label>
                <span>{{ viewData.requiredQty || 0 }} {{ viewData.materialUnit || '' }}</span>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="info-item">
                <label>包装容量：</label>
                <span>{{ viewData.packageCapacity || '-' }}</span>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="info-item">
                <label>单价：</label>
                <span>{{ viewData.unitPrice ? '¥' + parseFloat(viewData.unitPrice).toFixed(2) : '-' }}</span>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="info-item">
                <label>税率：</label>
                <span>{{ viewData.taxRate ? viewData.taxRate + '%' : '-' }}</span>
              </div>
            </el-col>
          </el-row>
        </el-card>

        <!-- 时间信息 -->
        <el-card class="time-card" shadow="never">
          <div slot="header" class="section-header">
            <i class="el-icon-time"></i>
            <span>时间信息</span>
          </div>
          <el-row :gutter="20">
            <el-col :span="12">
              <div class="info-item">
                <label>要求到货时间：</label>
                <span>{{ viewData.requiredDeliveryTime || '-' }}</span>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="info-item">
                <label>计划发货时间：</label>
                <span>{{ viewData.plannedDeliveryTime || '-' }}</span>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="info-item">
                <label>实际发货时间：</label>
                <span>{{ viewData.actualShipmentTime || '-' }}</span>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="info-item">
                <label>实际到货时间：</label>
                <span>{{ viewData.actualDeliveryTime || '-' }}</span>
              </div>
            </el-col>
          </el-row>
        </el-card>

        <!-- 状态信息 -->
        <el-card class="status-card" shadow="never">
          <div slot="header" class="section-header">
            <i class="el-icon-s-check"></i>
            <span>状态信息</span>
          </div>
          <el-row :gutter="20">
            <el-col :span="12">
              <div class="info-item">
                <label>业务状态：</label>
                <el-tag :type="getStatusTagType(viewData.businessStatus)">
                  {{ getStatusLabel(viewData.businessStatus) }}
                </el-tag>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="info-item">
                <label>确认状态：</label>
                <el-tag :type="viewData.senderConfirmStatus === 1 ? 'success' : viewData.senderConfirmStatus === 2 ? 'danger' : 'info'">
                  {{ viewData.senderConfirmStatus === 1 ? '已确认' : viewData.senderConfirmStatus === 2 ? '已拒绝' : '未确认' }}
                </el-tag>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="info-item">
                <label>当前信息：</label>
                <span>{{ viewData.currentInfo || '-' }}</span>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="info-item">
                <label>创建时间：</label>
                <span>{{ viewData.createTime || '-' }}</span>
              </div>
            </el-col>
          </el-row>
        </el-card>

        <!-- 备注信息 -->
        <el-card class="remark-card" shadow="never" v-if="viewData.remark">
          <div slot="header" class="section-header">
            <i class="el-icon-document"></i>
            <span>备注信息</span>
          </div>
          <div class="remark-content">
            {{ viewData.remark }}
          </div>
        </el-card>

        <!-- 操作按钮区域 -->
        <div class="drawer-footer">
          <el-button @click="handleViewDrawerClose">关闭</el-button>
          <el-button 
            type="primary" 
            @click="handleEditFromView" 
            v-if="viewData.businessStatus === 10"
            v-hasPermi="['kanban:order:edit']"
          >
            编辑
          </el-button>
          <el-button 
            type="success" 
            @click="handleConfirmFromView" 
            v-if="viewData.businessStatus === 20 && viewData.senderConfirmStatus === 0"
            v-hasPermi="['kanban:order:confirm']"
          >
            确认
          </el-button>
          <el-button 
            type="warning" 
            @click="handlePrintFromView" 
            v-if="viewData.businessStatus >= 30"
            v-hasPermi="['kanban:order:print']"
          >
            打印
          </el-button>
        </div>
      </div>
    </el-drawer>

    <!-- 编辑看板抽屉 -->
    <el-drawer
      title="编辑看板订单"
      :visible.sync="editDrawerVisible"
      direction="rtl"
      size="60%"
      :before-close="handleEditDrawerClose"
      :close-on-click-modal="false"
    >
      <div class="drawer-content">
        <el-form
          ref="editForm"
          :model="editForm"
          :rules="editRules"
          label-width="120px"
          class="kanban-form"
        >
          <!-- 协议信息区域 -->
          <el-card class="form-section" shadow="never">
            <div slot="header" class="section-header">
              <i class="el-icon-document"></i>
              <span>协议信息</span>
            </div>
            <el-row :gutter="20">
              <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                <el-form-item label="供货协议编号" prop="frameworkCode" required>
                  <el-input v-model="editForm.frameworkCode" readonly>
                    <el-button slot="append" icon="el-icon-search" @click="openFrameworkDialog('edit')">选择</el-button>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                <el-form-item label="看板编号" prop="kanbanCode">
                  <el-input v-model="editForm.kanbanCode" readonly />
                </el-form-item>
              </el-col>
            </el-row>
          </el-card>

          <!-- 基础信息区域 -->
          <el-card class="form-section" shadow="never">
            <div slot="header" class="section-header">
              <i class="el-icon-office-building"></i>
              <span>基础信息</span>
            </div>
            <el-row :gutter="20">
              <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                <el-form-item label="要货公司" prop="receiverCompanyName">
                  <el-input v-model="editForm.receiverCompanyName" readonly />
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                <el-form-item label="发货公司" prop="senderCompanyName">
                  <el-input v-model="editForm.senderCompanyName" readonly />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                <el-form-item label="收货联系人" prop="receiverContact">
                  <el-input v-model="editForm.receiverContact" placeholder="请输入收货联系人" />
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                <el-form-item label="收货联系电话" prop="receiverPhone">
                  <el-input v-model="editForm.receiverPhone" placeholder="请输入收货联系电话" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                <el-form-item label="发货联系人" prop="senderContact">
                  <el-input v-model="editForm.senderContact" placeholder="请输入发货联系人" />
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                <el-form-item label="发货联系电话" prop="senderPhone">
                  <el-input v-model="editForm.senderPhone" placeholder="请输入发货联系电话" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-card>

          <!-- 物料信息区域 -->
          <el-card class="form-section" shadow="never">
            <div slot="header" class="section-header">
              <i class="el-icon-goods"></i>
              <span>物料信息</span>
            </div>
            <el-row :gutter="20">
              <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                <el-form-item label="物料编码" prop="materialCode" required>
                  <el-select
                    v-model="editForm.materialCode"
                    placeholder="请选择物料编码"
                    filterable
                    clearable
                    style="width: 100%"
                    @change="handleEditMaterialChange"
                  >
                    <el-option
                      v-for="item in materialOptions"
                      :key="item.code"
                      :label="item.code + ' - ' + item.name"
                      :value="item.code"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                <el-form-item label="物料名称" prop="materialName">
                  <el-input v-model="editForm.materialName" readonly />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :xs="24" :sm="8" :md="8" :lg="8" :xl="8">
                <el-form-item label="计量单位" prop="materialUnit">
                  <el-input v-model="editForm.materialUnit" readonly />
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="8" :md="8" :lg="8" :xl="8">
                <el-form-item label="包装型号" prop="packageType">
                  <el-input v-model="editForm.packageType" placeholder="请输入包装型号" />
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="8" :md="8" :lg="8" :xl="8">
                <el-form-item label="包装容量" prop="packageCapacity">
                  <el-input-number
                    v-model="editForm.packageCapacity"
                    :min="1"
                    :precision="2"
                    style="width: 100%"
                    placeholder="请输入包装容量"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :xs="24" :sm="8" :md="8" :lg="8" :xl="8">
                <el-form-item label="要货数量" prop="requiredQty" required>
                  <el-input-number
                    v-model="editForm.requiredQty"
                    :min="1"
                    :precision="2"
                    style="width: 100%"
                    placeholder="请输入要货数量"
                    @change="calculateEditTotalPrice"
                  />
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="8" :md="8" :lg="8" :xl="8">
                <el-form-item label="不含税单价" prop="unitPrice">
                  <el-input-number
                    v-model="editForm.unitPrice"
                    :min="0"
                    :precision="4"
                    style="width: 100%"
                    placeholder="请输入不含税单价"
                    @change="calculateEditTotalPrice"
                  />
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="8" :md="8" :lg="8" :xl="8">
                <el-form-item label="税率(%)" prop="taxRate">
                  <el-input-number
                    v-model="editForm.taxRate"
                    :min="0"
                    :max="100"
                    :precision="2"
                    style="width: 100%"
                    placeholder="请输入税率"
                    @change="calculateEditTotalPrice"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                <el-form-item label="含税总价">
                  <el-input v-model="editTotalPriceDisplay" readonly>
                    <template slot="append">元</template>
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-card>

          <!-- 时间配置区域 -->
          <el-card class="form-section" shadow="never">
            <div slot="header" class="section-header">
              <i class="el-icon-time"></i>
              <span>时间配置</span>
            </div>
            <el-row :gutter="20">
              <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                <el-form-item label="要求到货时间" prop="requiredDeliveryTime" required>
                  <el-date-picker
                    v-model="editForm.requiredDeliveryTime"
                    type="datetime"
                    placeholder="请选择要求到货时间"
                    format="yyyy-MM-dd HH:mm:ss"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    style="width: 100%"
                    @change="calculateEditPlannedDeliveryTime"
                  />
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                <el-form-item label="计划发货时间" prop="plannedDeliveryTime">
                  <el-date-picker
                    v-model="editForm.plannedDeliveryTime"
                    type="datetime"
                    placeholder="请选择计划发货时间"
                    format="yyyy-MM-dd HH:mm:ss"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </el-card>

          <!-- 备注信息 -->
          <el-card class="form-section" shadow="never">
            <div slot="header" class="section-header">
              <i class="el-icon-edit-outline"></i>
              <span>备注信息</span>
            </div>
            <el-form-item label="备注" prop="remark">
              <el-input
                v-model="editForm.remark"
                type="textarea"
                :rows="3"
                placeholder="请输入备注信息（可选）"
              />
            </el-form-item>
          </el-card>
        </el-form>

        <!-- 操作按钮区域 -->
        <div class="drawer-footer">
          <el-button @click="handleEditDrawerClose">取 消</el-button>
          <el-button type="info" @click="handleEditSaveDraft" :loading="editSaveLoading">保存草稿</el-button>
          <el-button type="primary" @click="handleEditSubmit" :loading="editSubmitLoading">确认创建</el-button>
        </div>
      </div>
    </el-drawer>

    <!-- 新增看板抽屉 -->
    <el-drawer
      title="新增看板订单"
      :visible.sync="addDrawerVisible"
      direction="rtl"
      size="60%"
      :before-close="handleDrawerClose"
      :close-on-click-modal="false"
    >
      <div class="drawer-content">
        <el-form
          ref="addForm"
          :model="addForm"
          :rules="addRules"
          label-width="120px"
          size="small"
        >
          <!-- 协议选择区域 -->
          <el-card class="form-section" shadow="never">
            <div slot="header" class="section-header">
              <i class="el-icon-document"></i>
              <span>协议选择</span>
            </div>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="供货协议" prop="frameworkId" required>
                  <el-select
                    v-model="addForm.frameworkId"
                    placeholder="请选择供货协议"
                    filterable
                    clearable
                    style="width: 100%"
                    @change="handleFrameworkChange"
                    @focus="openFrameworkDialog"
                  >
                    <el-option
                      v-for="item in frameworkOptions"
                      :key="item.id"
                      :label="item.frameworkCode + ' - ' + item.frameworkName"
                      :value="item.id"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="协议状态">
                  <el-tag v-if="selectedFramework" :type="selectedFramework.status === 0 ? 'success' : 'info'">
                    {{ selectedFramework.status === 0 ? '生效' : '未生效' }}
                  </el-tag>
                </el-form-item>
              </el-col>
            </el-row>
            <!-- 协议信息展示 -->
            <div v-if="selectedFramework" class="framework-info">
              <el-descriptions :column="2" size="small" border>
                <el-descriptions-item label="协议编号">{{ selectedFramework.frameworkCode }}</el-descriptions-item>
                <el-descriptions-item label="协议名称">{{ selectedFramework.frameworkName }}</el-descriptions-item>
                <el-descriptions-item label="要货公司">{{ selectedFramework.receiverCompanyName }}</el-descriptions-item>
                <el-descriptions-item label="发货公司">{{ selectedFramework.senderCompanyName }}</el-descriptions-item>
              </el-descriptions>
            </div>
          </el-card>

          <!-- 基础信息区域 -->
          <el-card class="form-section" shadow="never">
            <div slot="header" class="section-header">
              <i class="el-icon-office-building"></i>
              <span>基础信息</span>
            </div>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="要货公司" prop="receiverCompanyName">
                  <el-input v-model="addForm.receiverCompanyName" readonly />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="发货公司" prop="senderCompanyName">
                  <el-input v-model="addForm.senderCompanyName" readonly />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="需求计划部门" prop="receiverDeptId">
                  <treeselect v-model="addForm.receiverDeptId" :options="deptOptions" :normalizer="normalizer"
                    placeholder="请选择需求计划部门" @input="handleReceiverDeptChange" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="发货计划部门" prop="senderDeptId">
                  <treeselect
                    v-model="addForm.senderDeptId"
                    :options="deptOptions"
                    :normalizer="normalizer"
                    :show-count="true"
                    placeholder="请选择发货计划部门"
                    @input="handleSenderDeptChange"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="收货仓库" prop="receiverWarehouseName">
                  <el-input v-model="addForm.receiverWarehouseName" placeholder="请输入收货仓库" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="发货仓库" prop="senderWarehouseName">
                  <el-input v-model="addForm.senderWarehouseName" placeholder="请输入发货仓库" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="收货联系人" prop="receiverContact">
                  <el-input v-model="addForm.receiverContact" placeholder="请输入收货联系人" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="发货联系人" prop="senderContact">
                  <el-input v-model="addForm.senderContact" placeholder="请输入发货联系人" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="收货联系电话" prop="receiverPhone">
                  <el-input v-model="addForm.receiverPhone" placeholder="请输入收货联系电话" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="发货联系电话" prop="senderPhone">
                  <el-input v-model="addForm.senderPhone" placeholder="请输入发货联系电话" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-card>

          <!-- 物料信息区域 -->
          <el-card class="form-section" shadow="never">
            <div slot="header" class="section-header">
              <i class="el-icon-goods"></i>
              <span>物料信息</span>
            </div>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="物料编码" prop="materialCode" required>
                  <el-select
                    v-model="addForm.materialCode"
                    placeholder="请选择物料编码"
                    filterable
                    clearable
                    style="width: 100%"
                    @change="handleMaterialChange"
                  >
                    <el-option
                      v-for="item in materialOptions"
                      :key="item.code"
                      :label="item.code + ' - ' + item.name"
                      :value="item.code"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="物料名称" prop="materialName">
                  <el-input v-model="addForm.materialName" readonly />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="计量单位" prop="materialUnit">
                  <el-input v-model="addForm.materialUnit" readonly />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="包装型号" prop="packageType">
                  <el-input v-model="addForm.packageType" placeholder="请输入包装型号" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="包装容量" prop="packageCapacity">
                  <el-input-number
                    v-model="addForm.packageCapacity"
                    :min="1"
                    :precision="2"
                    style="width: 100%"
                    placeholder="请输入包装容量"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="要货数量" prop="requiredQty" required>
                  <el-input-number
                    v-model="addForm.requiredQty"
                    :min="1"
                    :precision="2"
                    style="width: 100%"
                    placeholder="请输入要货数量"
                    @change="calculateTotalPrice"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="不含税单价" prop="unitPrice">
                  <el-input-number
                    v-model="addForm.unitPrice"
                    :min="0"
                    :precision="4"
                    style="width: 100%"
                    placeholder="请输入不含税单价"
                    @change="calculateTotalPrice"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="税率(%)" prop="taxRate">
                  <el-input-number
                    v-model="addForm.taxRate"
                    :min="0"
                    :max="100"
                    :precision="2"
                    style="width: 100%"
                    placeholder="请输入税率"
                    @change="calculateTotalPrice"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="含税总价">
                  <el-input v-model="totalPriceDisplay" readonly>
                    <template slot="append">元</template>
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-card>

          <!-- 时间配置区域 -->
          <el-card class="form-section" shadow="never">
            <div slot="header" class="section-header">
              <i class="el-icon-time"></i>
              <span>时间配置</span>
            </div>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="要求到货时间" prop="requiredDeliveryTime" required>
                  <el-date-picker
                    v-model="addForm.requiredDeliveryTime"
                    type="datetime"
                    placeholder="请选择要求到货时间"
                    format="yyyy-MM-dd HH:mm:ss"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    style="width: 100%"
                    @change="calculatePlannedDeliveryTime"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="计划发货时间" prop="plannedDeliveryTime">
                  <el-date-picker
                    v-model="addForm.plannedDeliveryTime"
                    type="datetime"
                    placeholder="请选择计划发货时间"
                    format="yyyy-MM-dd HH:mm:ss"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </el-card>

          <!-- 备注信息 -->
          <el-card class="form-section" shadow="never">
            <div slot="header" class="section-header">
              <i class="el-icon-edit-outline"></i>
              <span>备注信息</span>
            </div>
            <el-form-item label="备注" prop="remark">
              <el-input
                v-model="addForm.remark"
                type="textarea"
                :rows="3"
                placeholder="请输入备注信息（可选）"
              />
            </el-form-item>
          </el-card>
        </el-form>

        <!-- 操作按钮区域 -->
        <div class="drawer-footer">
          <el-button @click="handleDrawerClose">取 消</el-button>
          <el-button type="info" @click="handleSaveDraft" :loading="saveLoading">保存草稿</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitLoading">提交看板</el-button>
        </div>
      </div>
    </el-drawer>

    <!-- 供货协议选择弹窗 -->
    <el-dialog
      title="选择供货协议"
      :visible.sync="frameworkDialogVisible"
      width="80%"
      :close-on-click-modal="false"
      :before-close="handleFrameworkDialogClose"
    >
      <div class="framework-dialog-content">
        <!-- 搜索区域 -->
        <el-form :inline="true" :model="frameworkQuery" class="demo-form-inline">
          <el-form-item label="协议编号">
            <el-input
              v-model="frameworkQuery.frameworkCode"
              placeholder="请输入协议编号"
              clearable
              style="width: 200px"
              @keyup.enter.native="searchFrameworks"
            />
          </el-form-item>

          <el-form-item label="要货公司">
            <el-input
              v-model="frameworkQuery.receiverCompanyName"
              placeholder="请输入要货公司"
              clearable
              style="width: 200px"
              @keyup.enter.native="searchFrameworks"
            />
          </el-form-item>
          <el-form-item label="发货公司">
            <el-input
              v-model="frameworkQuery.senderCompanyName"
              placeholder="请输入发货公司"
              clearable
              style="width: 200px"
              @keyup.enter.native="searchFrameworks"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" @click="searchFrameworks">搜索</el-button>
            <el-button icon="el-icon-refresh" @click="resetFrameworkQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <!-- 协议列表 -->
        <el-table
          v-loading="frameworkLoading"
          :data="frameworkList"
          border
          highlight-current-row
          @current-change="handleFrameworkSelect"
          style="width: 100%; margin-top: 20px"
        >
          <el-table-column type="index" label="序号" width="60" align="center" />
          <el-table-column prop="frameworkCode" label="协议编号" width="150" />
          <el-table-column prop="receiverCompanyName" label="要货公司" width="150" />
          <el-table-column prop="senderCompanyName" label="发货公司" width="150" />
          <el-table-column prop="businessStartDate" label="生效时间" width="180">
            <template slot-scope="scope">
              {{ parseTime(scope.row.businessStartDate, '{y}-{m}-{d}') }}
            </template>
          </el-table-column>
          <el-table-column prop="businessEndDate" label="到期时间" width="180">
            <template slot-scope="scope">
              {{ parseTime(scope.row.businessEndDate, '{y}-{m}-{d}') }}
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" width="80" align="center">
            <template slot-scope="scope">
              <el-tag :type="scope.row.status === 0 ? 'success' : 'info'">
                {{ scope.row.status === 0 ? '生效' : '未生效' }}
              </el-tag>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <pagination
          v-show="frameworkTotal > 0"
          :total="frameworkTotal"
          :page.sync="frameworkQuery.pageNum"
          :limit.sync="frameworkQuery.pageSize"
          @pagination="getFrameworkList"
        />
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="handleFrameworkDialogClose">取 消</el-button>
        <el-button type="primary" @click="confirmFrameworkSelect" :disabled="!selectedFrameworkRow">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { 
  listKanbanOrder, 
  getKanbanOrder, 
  delKanbanOrder, 
  addKanbanOrder,
  updateKanbanOrder,
  exportKanbanOrder,
  confirmKanbanOrderBySender,
  printKanban,
  printBoxLabel
} from '@/api/kanban/kanbanOrder'
import { listSupplyFramework, listValidSupplyFramework } from '@/api/kanban/supplyFramework'
import { listDept } from '@/api/system/dept'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'

export default {
  name: 'KanbanOrderList',
  dicts: ['yaohuokb_business'],
  components: {
    Treeselect
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 看板订单表格数据
      list: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        kanbanCode: null,
        frameworkCode: null,
        receiverCompanyName: null,
        senderCompanyName: null,
        materialCode: null,
        materialName: null,
        businessStatus: null,
        senderConfirmStatus: null,
        createTimeRange: null,
        deliveryTimeRange: null
      },
    computed: {
      // 响应式抽屉尺寸
      drawerSize() {
        const width = window.innerWidth
        if (width < 768) {
          return '95%' // 手机端
        } else if (width < 1200) {
          return '80%' // 平板端
        } else {
          return '60%' // 桌面端
        }
      },
      // 新增表单总价显示
      totalPriceDisplay() {
        if (this.addForm.requiredQty && this.addForm.unitPrice && this.addForm.taxRate !== null) {
          const totalPrice = this.addForm.requiredQty * this.addForm.unitPrice * (1 + this.addForm.taxRate / 100)
          return totalPrice.toFixed(2)
        }
        return '0.00'
      },
      // 编辑表单总价显示
      editTotalPriceDisplay() {
        if (this.editForm.requiredQty && this.editForm.unitPrice && this.editForm.taxRate !== null) {
          const totalPrice = this.editForm.requiredQty * this.editForm.unitPrice * (1 + this.editForm.taxRate / 100)
          return totalPrice.toFixed(2)
        }
        return '0.00'
      }
    },
      // 确认对话框
      confirmDialogVisible: false,
      confirmLoading: false,
      confirmForm: {
        id: null,
        kanbanCode: '',
        confirmRemark: ''
      },
      // 打印对话框
      printDialogVisible: false,
      printLoading: false,
      currentPrintRow: null,
      // 查看抽屉
      viewDrawerVisible: false,
      viewLoading: false,
      viewData: {},
      // 新增看板抽屉
      addDrawerVisible: false,
      // 编辑看板抽屉
      editDrawerVisible: false,
      editLoading: false,
      // 供货协议选择弹窗
      frameworkDialogVisible: false,
      frameworkLoading: false,
      frameworkList: [],
      frameworkTotal: 0,
      selectedFrameworkRow: null,
      frameworkQuery: {
        pageNum: 1,
        pageSize: 10,
        frameworkCode: '',
        receiverCompanyName: '',
        senderCompanyName: ''
      },
      // 新增表单数据
      addForm: {
        frameworkId: null,
        receiverCompanyName: '',
        receiverCompanyId: null,
        senderCompanyName: '',
        senderCompanyId: null,
        receiverDeptId: null,
        receiverDeptName: '',
        senderDeptId: null,
        senderDeptName: '',
        receiverWarehouseName: '',
        senderWarehouseName: '',
        receiverContact: '',
        receiverPhone: '',
        senderContact: '',
        senderPhone: '',
        materialCode: '',
        materialName: '',
        materialUnit: '',
        packageType: '',
        packageCapacity: null,
        requiredQty: null,
        unitPrice: null,
        taxRate: 13,
        requiredDeliveryTime: '',
        plannedDeliveryTime: '',
        remark: ''
      },
      // 编辑表单数据
      editForm: {
        id: null,
        frameworkId: null,
        frameworkCode: '',
        kanbanCode: '',
        receiverCompanyName: '',
        receiverCompanyId: null,
        senderCompanyName: '',
        senderCompanyId: null,
        receiverDeptName: '',
        senderDeptName: '',
        receiverWarehouseName: '',
        senderWarehouseName: '',
        receiverContact: '',
        receiverPhone: '',
        senderContact: '',
        senderPhone: '',
        materialCode: '',
        materialName: '',
        materialUnit: '',
        packageType: '',
        packageCapacity: null,
        requiredQty: null,
        unitPrice: null,
        taxRate: 13,
        requiredDeliveryTime: '',
        plannedDeliveryTime: '',
        remark: ''
      },
      // 表单验证规则
      addRules: {
        frameworkId: [
          { required: true, message: '请选择供货协议', trigger: 'change' }
        ],
        receiverDeptId: [
          { required: true, message: '请选择需求计划部门', trigger: 'change' }
        ],
        senderDeptId: [
          { required: true, message: '请选择发货计划部门', trigger: 'change' }
        ],
        receiverWarehouseName: [
          { required: true, message: '请输入收货仓库', trigger: 'blur' },
          { min: 2, max: 50, message: '仓库名称长度在 2 到 50 个字符', trigger: 'blur' }
        ],
        senderWarehouseName: [
          { required: true, message: '请输入发货仓库', trigger: 'blur' },
          { min: 2, max: 50, message: '仓库名称长度在 2 到 50 个字符', trigger: 'blur' }
        ],
        receiverContact: [
          { required: true, message: '请输入收货联系人', trigger: 'blur' },
          { min: 2, max: 20, message: '联系人姓名长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        receiverPhone: [
          { required: true, message: '请输入收货联系电话', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
        ],
        senderContact: [
          { required: true, message: '请输入发货联系人', trigger: 'blur' },
          { min: 2, max: 20, message: '联系人姓名长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        senderPhone: [
          { required: true, message: '请输入发货联系电话', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
        ],
        materialCode: [
          { required: true, message: '请选择物料编码', trigger: 'change' }
        ],
        packageType: [
          { required: true, message: '请输入包装型号', trigger: 'blur' },
          { min: 1, max: 30, message: '包装型号长度在 1 到 30 个字符', trigger: 'blur' }
        ],
        packageCapacity: [
          { required: true, message: '请输入包装容量', trigger: 'blur' },
          { type: 'number', min: 0.01, message: '包装容量必须大于0', trigger: 'blur' }
        ],
        requiredQty: [
          { required: true, message: '请输入要货数量', trigger: 'blur' },
          { type: 'number', min: 0.01, message: '要货数量必须大于0', trigger: 'blur' }
        ],
        unitPrice: [
          { required: true, message: '请输入不含税单价', trigger: 'blur' },
          { type: 'number', min: 0, message: '单价不能为负数', trigger: 'blur' }
        ],
        taxRate: [
          { required: true, message: '请输入税率', trigger: 'blur' },
          { type: 'number', min: 0, max: 100, message: '税率必须在0-100之间', trigger: 'blur' }
        ],
        requiredDeliveryTime: [
          { required: true, message: '请选择要求到货时间', trigger: 'change' }
        ],
        remark: [
          { max: 500, message: '备注信息不能超过500个字符', trigger: 'blur' }
        ]
      },
      // 编辑表单验证规则
      editRules: {
        frameworkCode: [
          { required: true, message: '请选择供货协议', trigger: 'change' }
        ],
        receiverDeptName: [
          { required: true, message: '请输入需求计划部门', trigger: 'blur' },
          { min: 2, max: 50, message: '部门名称长度在 2 到 50 个字符', trigger: 'blur' }
        ],
        senderDeptName: [
          { required: true, message: '请输入发货计划部门', trigger: 'blur' },
          { min: 2, max: 50, message: '部门名称长度在 2 到 50 个字符', trigger: 'blur' }
        ],
        receiverWarehouseName: [
          { required: true, message: '请输入收货仓库', trigger: 'blur' },
          { min: 2, max: 50, message: '仓库名称长度在 2 到 50 个字符', trigger: 'blur' }
        ],
        senderWarehouseName: [
          { required: true, message: '请输入发货仓库', trigger: 'blur' },
          { min: 2, max: 50, message: '仓库名称长度在 2 到 50 个字符', trigger: 'blur' }
        ],
        receiverContact: [
          { required: true, message: '请输入收货联系人', trigger: 'blur' },
          { min: 2, max: 20, message: '联系人姓名长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        receiverPhone: [
          { required: true, message: '请输入收货联系电话', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
        ],
        senderContact: [
          { required: true, message: '请输入发货联系人', trigger: 'blur' },
          { min: 2, max: 20, message: '联系人姓名长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        senderPhone: [
          { required: true, message: '请输入发货联系电话', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
        ],
        materialCode: [
          { required: true, message: '请选择物料编码', trigger: 'change' }
        ],
        packageType: [
          { required: true, message: '请输入包装型号', trigger: 'blur' },
          { min: 1, max: 30, message: '包装型号长度在 1 到 30 个字符', trigger: 'blur' }
        ],
        packageCapacity: [
          { required: true, message: '请输入包装容量', trigger: 'blur' },
          { type: 'number', min: 0.01, message: '包装容量必须大于0', trigger: 'blur' }
        ],
        requiredQty: [
          { required: true, message: '请输入要货数量', trigger: 'blur' },
          { type: 'number', min: 0.01, message: '要货数量必须大于0', trigger: 'blur' }
        ],
        unitPrice: [
          { required: true, message: '请输入不含税单价', trigger: 'blur' },
          { type: 'number', min: 0, message: '单价不能为负数', trigger: 'blur' }
        ],
        taxRate: [
          { required: true, message: '请输入税率', trigger: 'blur' },
          { type: 'number', min: 0, max: 100, message: '税率必须在0-100之间', trigger: 'blur' }
        ],
        requiredDeliveryTime: [
          { required: true, message: '请选择要求到货时间', trigger: 'change' }
        ],
        remark: [
          { max: 500, message: '备注信息不能超过500个字符', trigger: 'blur' }
        ]
      },
      // 协议选项
      frameworkOptions: [],
      // 选中的协议信息
      selectedFramework: null,
      // 物料选项
      materialOptions: [],
      // 部门选项
      deptOptions: [],
      // 保存和提交状态
      saveLoading: false,
      submitLoading: false,
      // 编辑保存和提交状态
      editSaveLoading: false,
      editSubmitLoading: false
    }
  },
  created() {
    console.log('=== 看板订单页面组件已创建 ===')
    console.log('当前路由:', this.$route)
    console.log('路由路径:', this.$route.path)
    console.log('路由名称:', this.$route.name)
    console.log('用户权限:', this.$store.getters.permissions)
    console.log('是否有看板订单列表权限:', this.$store.getters.permissions.includes('kanban:order:list'))
    console.log('准备调用getList方法...')
    this.getList()
    this.getDeptList()
  },
  methods: {
    /** 查询看板订单列表 */
    getList() {
      console.log('开始获取看板订单列表...')
      console.log('当前queryParams:', this.queryParams)
      this.loading = true
      // 处理时间参数
      const params = { ...this.queryParams }
      
      // 处理创建时间范围
      if (this.queryParams.createTimeRange && this.queryParams.createTimeRange.length === 2) {
        params.beginCreateTime = this.queryParams.createTimeRange[0]
        params.endCreateTime = this.queryParams.createTimeRange[1]
      }
      
      // 处理要求到货时间范围
      if (this.queryParams.deliveryTimeRange && this.queryParams.deliveryTimeRange.length === 2) {
        params.beginRequiredDeliveryTime = this.queryParams.deliveryTimeRange[0]
        params.endRequiredDeliveryTime = this.queryParams.deliveryTimeRange[1]
      }
      
      // 移除范围字段，避免传递到后端
      delete params.createTimeRange
      delete params.deliveryTimeRange
      
      console.log('发送API请求参数:', params)
      
      listKanbanOrder(params).then(response => {
        console.log('API响应成功:', response)
        this.list = response.rows
        this.total = response.total
        this.loading = false
        console.log('数据加载完成，列表长度:', this.list ? this.list.length : 0)
      }).catch(error => {
        console.error('获取看板订单列表失败:', error)
        console.error('错误详情:', error.response || error.message || error)
        this.$modal.msgError('获取数据失败，请检查网络连接或联系管理员')
        this.loading = false
      })
    },
    /** 关闭查看抽屉 */
    handleViewDrawerClose() {
      this.viewDrawerVisible = false
      this.viewData = {}
    },
    /** 从查看抽屉编辑订单 */
    handleEditFromView() {
      this.handleViewDrawerClose()
      this.handleEdit(this.viewData)
    },
    /** 从查看抽屉确认订单 */
    handleConfirmFromView() {
      this.handleConfirm(this.viewData)
      this.handleViewDrawerClose()
    },
    /** 从查看抽屉打印订单 */
    handlePrintFromView() {
      this.handlePrint(this.viewData)
      this.handleViewDrawerClose()
    },
    /** 获取状态标签类型 */
    getStatusTagType(status) {
      const statusMap = {
        10: 'info',     // 草稿
        20: 'warning',  // 已创建
        30: 'primary',  // 已确认
        40: 'success',  // 已发货
        50: 'warning',  // 部分收货
        60: 'success',  // 全部收货
        '-10': 'danger' // 已作废
      }
      return statusMap[status] || 'info'
    },
    /** 获取状态标签文本 */
    getStatusLabel(status) {
      const statusMap = {
        10: '草稿',
        20: '已创建',
        30: '已确认',
        40: '已发货',
        50: '部分收货',
        60: '全部收货',
        '-10': '已作废'
      }
      return statusMap[status] || '未知状态'
    },
    /** 获取状态步骤 */
    getStatusStep(status) {
      const stepMap = {
        10: 0,  // 草稿
        20: 1,  // 已创建
        30: 2,  // 已确认
        40: 3,  // 已发货
        50: 4,  // 部分收货
        60: 5,  // 全部收货
        '-10': -1 // 已作废
      }
      return stepMap[status] || 0
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.resetAddForm()
      this.addDrawerVisible = true
      this.loadFrameworkOptions()
    },
    /** 查看按钮操作 */
    handleView(row) {
      this.viewLoading = true
      this.viewDrawerVisible = true
      // 获取订单详情
      getKanbanOrder(row.id).then(response => {
        this.viewData = response.data
        this.viewLoading = false
      }).catch(error => {
        console.error('获取订单详情失败:', error)
        this.$modal.msgError('获取订单详情失败')
        this.viewLoading = false
        this.viewDrawerVisible = false
      })
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.$router.push('/kanban/kanbanOrder/edit/' + row.id)
    },
    /** 查看协议 */
    viewFramework(frameworkId) {
      this.$router.push('/kanban/supplyFramework/detail/' + frameworkId)
    },
    /** 确认按钮操作 */
    handleConfirm(row) {
      this.confirmForm = {
        id: row.id,
        kanbanCode: row.kanbanCode,
        confirmRemark: ''
      }
      this.confirmDialogVisible = true
    },
    /** 提交确认 */
    submitConfirm() {
      this.confirmLoading = true
      confirmKanbanOrderBySender(this.confirmForm.id, this.confirmForm.confirmRemark).then(response => {
        this.$modal.msgSuccess('确认成功')
        this.confirmDialogVisible = false
        this.getList()
      }).finally(() => {
        this.confirmLoading = false
      })
    },
    /** 打印按钮操作 */
    handlePrint(row) {
      this.currentPrintRow = row
      this.printDialogVisible = true
    },
    /** 执行打印 */
    doPrint(type) {
      this.printLoading = true
      const printApi = type === 'kanban' ? printKanban : printBoxLabel
      const printName = type === 'kanban' ? '看板' : '箱标'
      
      printApi(this.currentPrintRow.id).then(response => {
        this.$modal.msgSuccess(`${printName}打印成功`)
        this.printDialogVisible = false
        this.getList()
      }).finally(() => {
        this.printLoading = false
      })
    },
    /** 作废按钮操作 */
    handleVoid(row) {
      this.$modal.confirm('是否确认作废看板编号为"' + row.kanbanCode + '"的数据项？').then(function() {
        // 这里应该调用作废接口，暂时使用删除接口
        return delKanbanOrder(row.id)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('作废成功')
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.$modal.confirm('是否确认导出所有看板订单数据项？').then(() => {
        this.loading = true
        return exportKanbanOrder(this.queryParams)
      }).then(response => {
        this.$download.excel(response, '看板订单数据.xlsx')
      }).catch(() => {}).finally(() => {
        this.loading = false
      })
    },
    /** 重置新增表单 */
    resetAddForm() {
      this.addForm = {
        frameworkId: null,
        receiverCompanyName: '',
        senderCompanyName: '',
        receiverDeptName: '',
        senderDeptName: '',
        receiverWarehouseName: '',
        senderWarehouseName: '',
        receiverContact: '',
        receiverPhone: '',
        senderContact: '',
        senderPhone: '',
        materialCode: '',
        materialName: '',
        materialUnit: '',
        packageType: '',
        packageCapacity: null,
        requiredQty: null,
        unitPrice: null,
        taxRate: 13,
        requiredDeliveryTime: '',
        plannedDeliveryTime: '',
        remark: ''
      }
      this.selectedFramework = null
      this.materialOptions = []
      if (this.$refs.addForm) {
        this.$refs.addForm.resetFields()
      }
    },
    /** 关闭抽屉 */
    handleDrawerClose() {
      this.$modal.confirm('确定要关闭吗？未保存的数据将丢失。').then(() => {
        this.addDrawerVisible = false
        this.resetAddForm()
      }).catch(() => {})
    },
    /** 加载协议选项 */
    loadFrameworkOptions() {
      listSupplyFramework({ status: 1 }).then(response => {
        this.frameworkOptions = response.rows || []
      }).catch(error => {
        console.error('获取协议列表失败:', error)
        this.$modal.msgError('获取协议列表失败')
        this.frameworkOptions = []
      })
    },
    /** 获取部门列表 */
    getDeptList() {
      listDept().then(response => {
        this.deptOptions = this.handleTree(response.data, 'deptId')
      })
    },
    /** 转换部门数据为树形结构 */
    handleTree(data, id, parentId, children) {
      const config = {
        id: id || 'id',
        parentId: parentId || 'parentId',
        childrenList: children || 'children'
      }

      const childrenListMap = {}
      const nodeIds = {}
      const tree = []

      for (const d of data) {
        const parentId = d[config.parentId]
        if (childrenListMap[parentId] == null) {
          childrenListMap[parentId] = []
        }
        nodeIds[d[config.id]] = d
        childrenListMap[parentId].push(d)
      }

      for (const d of data) {
        const parentId = d[config.parentId]
        if (nodeIds[parentId] == null) {
          tree.push(d)
        }
      }

      for (const t of tree) {
        adaptToChildrenList(t)
      }

      function adaptToChildrenList(o) {
        if (childrenListMap[o[config.id]] !== null) {
          o[config.childrenList] = childrenListMap[o[config.id]]
        }
        if (o[config.childrenList]) {
          for (const c of o[config.childrenList]) {
            adaptToChildrenList(c)
          }
        }
      }
      return tree
    },
    /** 转换部门数据 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children
      }
      return {
        id: node.deptId,
        label: node.deptName,
        children: node.children
      }
    },
    /** 查找对应的公司节点 */
    findCompanyNode(node) {
      if (!node) return null

      // 如果当前节点的parent_id为0，说明它就是顶级公司
      if (node.parentId === 0) {
        return node
      }

      // 如果当前节点的parent_id为100（若依科技的ID），说明它是子公司
      if (node.parentId === 100) {
        return node
      }

      // 否则向上查找父节点
      const parentNode = this.findNodeById(this.deptOptions, node.parentId)
      if (parentNode) {
        return this.findCompanyNode(parentNode)
      }

      return null
    },
    /** 需求部门选择处理 */
    handleReceiverDeptChange(value) {
      if (value) {
        const selectedNode = this.findNodeById(this.deptOptions, value)
        if (selectedNode) {
          // 查找对应的公司名称
          const companyNode = this.findCompanyNode(selectedNode)
          if (companyNode) {
            // 设置公司名称和ID
            this.addForm.receiverCompanyName = companyNode.deptName
            this.addForm.receiverCompanyId = companyNode.deptId
          } else {
            // 如果找不到公司，使用当前部门作为公司
            this.addForm.receiverCompanyName = selectedNode.deptName
            this.addForm.receiverCompanyId = selectedNode.deptId
          }

          // 自动填充需求部门名称
          this.addForm.receiverDeptName = selectedNode.deptName
          // 自动填充收货仓库为选择的部门名称
          this.addForm.receiverWarehouseName = selectedNode.deptName
          // 自动填充收货联系人为部门负责人
          this.addForm.receiverContact = selectedNode.leader || ''
          // 自动填充收货电话为部门电话
          this.addForm.receiverPhone = selectedNode.phone || ''
        }
      } else {
        // 清空相关字段
        this.addForm.receiverDeptName = ''
        this.addForm.receiverCompanyName = ''
        this.addForm.receiverCompanyId = ''
        this.addForm.receiverWarehouseName = ''
        this.addForm.receiverContact = ''
        this.addForm.receiverPhone = ''
      }
    },
    /** 发货部门选择处理 */
    handleSenderDeptChange(value) {
      if (value) {
        const selectedNode = this.findNodeById(this.deptOptions, value)
        if (selectedNode) {
          // 查找对应的公司名称
          const companyNode = this.findCompanyNode(selectedNode)
          if (companyNode) {
            // 设置公司名称和ID
            this.addForm.senderCompanyName = companyNode.deptName
            this.addForm.senderCompanyId = companyNode.deptId
          } else {
            // 如果找不到公司，使用当前部门作为公司
            this.addForm.senderCompanyName = selectedNode.deptName
            this.addForm.senderCompanyId = selectedNode.deptId
          }

          // 自动填充发货部门名称
          this.addForm.senderDeptName = selectedNode.deptName
          // 自动填充发货仓库为选择的部门名称
          this.addForm.senderWarehouseName = selectedNode.deptName
          // 自动填充发货联系人为部门负责人
          this.addForm.senderContact = selectedNode.leader || ''
          // 自动填充发货电话为部门电话
          this.addForm.senderPhone = selectedNode.phone || ''
        }
      } else {
        // 清空相关字段
        this.addForm.senderDeptName = ''
        this.addForm.senderCompanyName = ''
        this.addForm.senderCompanyId = ''
        this.addForm.senderWarehouseName = ''
        this.addForm.senderContact = ''
        this.addForm.senderPhone = ''
      }
    },

    /** 根据ID查找节点 */
    findNodeById(tree, id) {
      for (const node of tree) {
        if (node.deptId === id) {
          return node
        }
        if (node.children && node.children.length > 0) {
          const found = this.findNodeById(node.children, id)
          if (found) {
            return found
          }
        }
      }
      return null
    },
    /** 协议选择变化 */
    handleFrameworkChange(frameworkId) {
      this.selectedFramework = this.frameworkOptions.find(item => item.id === frameworkId)
      if (this.selectedFramework) {
        this.addForm.receiverCompanyName = this.selectedFramework.receiverCompanyName
        this.addForm.senderCompanyName = this.selectedFramework.senderCompanyName
        this.loadMaterialOptions(frameworkId)
      }
    },
    /** 加载物料选项 */
    loadMaterialOptions(frameworkId) {
      // 这里需要调用获取物料列表的API
      // 暂时使用模拟数据
      this.materialOptions = [
        {
          code: 'MAT001',
          name: '钢材A型',
          unit: '吨',
          price: 5000,
          specification: 'Q235B',
          brand: '宝钢',
          category: '钢材'
        },
        {
          code: 'MAT002',
          name: '铝材B型',
          unit: '公斤',
          price: 25,
          specification: '6061-T6',
          brand: '中铝',
          category: '有色金属'
        },
        {
          code: 'MAT003',
          name: '塑料C型',
          unit: '个',
          price: 10,
          specification: 'ABS',
          brand: '巴斯夫',
          category: '塑料制品'
        },
        {
          code: 'MAT004',
          name: '螺栓M8*20',
          unit: '个',
          price: 0.5,
          specification: 'M8*20',
          brand: '标准件',
          category: '紧固件'
        },
        {
          code: 'MAT005',
          name: '电缆线3*2.5',
          unit: '米',
          price: 8.5,
          specification: '3*2.5mm²',
          brand: '远东',
          category: '电气材料'
        }
      ]
    },
    /** 物料选择变化 */
    handleMaterialChange(materialCode) {
      const material = this.materialOptions.find(item => item.code === materialCode)
      if (material) {
        this.addForm.materialName = material.name
        this.addForm.materialUnit = material.unit
        this.addForm.unitPrice = material.price
        // 重新计算总价
        this.calculateTotalPrice()
      } else {
        this.addForm.materialName = ''
        this.addForm.materialUnit = ''
        this.addForm.unitPrice = null
      }
    },
    /** 计算总价 */
    calculateTotalPrice() {
      if (this.addForm.requiredQty && this.addForm.unitPrice && this.addForm.taxRate !== null) {
        const subtotal = this.addForm.requiredQty * this.addForm.unitPrice
        const tax = subtotal * (this.addForm.taxRate / 100)
        const total = subtotal + tax
        this.totalPriceDisplay = total.toFixed(2)
      } else {
        this.totalPriceDisplay = '0.00'
      }
    },
    /** 计算计划发货时间 */
    calculatePlannedDeliveryTime() {
      if (this.addForm.requiredDeliveryTime) {
        // 默认提前1天发货
        const deliveryDate = new Date(this.addForm.requiredDeliveryTime)
        deliveryDate.setDate(deliveryDate.getDate() - 1)
        
        // 检查是否为周末，如果是则继续提前
        while (deliveryDate.getDay() === 0 || deliveryDate.getDay() === 6) {
          deliveryDate.setDate(deliveryDate.getDate() - 1)
        }
        
        // 格式化为字符串
        const year = deliveryDate.getFullYear()
        const month = String(deliveryDate.getMonth() + 1).padStart(2, '0')
        const day = String(deliveryDate.getDate()).padStart(2, '0')
        const hours = String(deliveryDate.getHours()).padStart(2, '0')
        const minutes = String(deliveryDate.getMinutes()).padStart(2, '0')
        const seconds = String(deliveryDate.getSeconds()).padStart(2, '0')
        
        this.addForm.plannedDeliveryTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
      } else {
        this.addForm.plannedDeliveryTime = ''
      }
    },
    /** 保存草稿 */
    handleSaveDraft() {
      this.$refs.addForm.validate((valid) => {
        if (valid) {
          this.saveLoading = true
          // 准备提交数据
          const formData = { 
            ...this.addForm, 
            businessStatus: 0, // 0表示草稿状态
            totalPrice: this.totalPriceDisplay
          }
          
          addKanbanOrder(formData).then(response => {
            this.$modal.msgSuccess('保存草稿成功')
            this.addDrawerVisible = false
            this.resetAddForm()
            this.getList()
          }).catch(error => {
            console.error('保存草稿失败:', error)
            this.$modal.msgError('保存草稿失败，请重试')
          }).finally(() => {
            this.saveLoading = false
          })
        } else {
          this.$modal.msgError('请完善必填信息')
        }
      })
    },
    /** 打开供货协议选择弹窗 */
    openFrameworkDialog() {
      this.frameworkDialogVisible = true
      this.selectedFrameworkRow = null
      this.resetFrameworkQuery()
      this.getFrameworkList()
    },
    /** 关闭供货协议选择弹窗 */
    handleFrameworkDialogClose() {
      this.frameworkDialogVisible = false
      this.selectedFrameworkRow = null
      this.frameworkList = []
    },
    /** 获取有效协议列表 */
    getFrameworkList() {
      this.frameworkLoading = true
      listValidSupplyFramework(this.frameworkQuery).then(response => {
        this.frameworkList = response.rows || []
        this.frameworkTotal = response.total || 0
      }).catch(error => {
        console.error('获取有效协议列表失败:', error)
        this.$modal.msgError('获取协议列表失败')
        this.frameworkList = []
        this.frameworkTotal = 0
      }).finally(() => {
        this.frameworkLoading = false
      })
    },
    /** 搜索协议 */
    searchFrameworks() {
      this.frameworkQuery.pageNum = 1
      this.getFrameworkList()
    },
    /** 重置搜索条件 */
    resetFrameworkQuery() {
      this.frameworkQuery = {
        pageNum: 1,
        pageSize: 10,
        frameworkCode: '',
        receiverCompanyName: '',
        senderCompanyName: ''
      }
      this.getFrameworkList()
    },
    /** 选择协议行 */
    handleFrameworkSelect(row) {
      this.selectedFrameworkRow = row
    },
    /** 确认选择协议 */
    confirmFrameworkSelect() {
      if (this.selectedFrameworkRow) {
        this.addForm.frameworkId = this.selectedFrameworkRow.id
        this.handleFrameworkChange(this.selectedFrameworkRow.id)
        // 更新frameworkOptions中的选中项
        const existingIndex = this.frameworkOptions.findIndex(item => item.id === this.selectedFrameworkRow.id)
        if (existingIndex === -1) {
          this.frameworkOptions.push(this.selectedFrameworkRow)
        }
        this.frameworkDialogVisible = false
      }
    },
    /** 提交看板 */
    handleSubmit() {
      this.$refs.addForm.validate((valid) => {
        if (valid) {
          // 额外验证必要字段
          if (!this.addForm.frameworkId) {
            this.$modal.msgError('请选择供货协议')
            return
          }
          if (!this.addForm.materialCode) {
            this.$modal.msgError('请选择物料')
            return
          }
          if (!this.addForm.requiredQty || this.addForm.requiredQty <= 0) {
            this.$modal.msgError('请输入正确的需求数量')
            return
          }
          if (!this.addForm.requiredDeliveryTime) {
            this.$modal.msgError('请选择要求到货时间')
            return
          }
          
          this.submitLoading = true
          // 准备提交数据
          const formData = { 
            ...this.addForm, 
            businessStatus: 1, // 1表示已提交状态
            totalPrice: this.totalPriceDisplay
          }
          
          addKanbanOrder(formData).then(response => {
            this.$modal.msgSuccess('提交看板成功')
            this.addDrawerVisible = false
            this.resetAddForm()
            this.getList()
          }).catch(error => {
            console.error('提交看板失败:', error)
            this.$modal.msgError('提交看板失败，请重试')
          }).finally(() => {
            this.submitLoading = false
          })
        } else {
          this.$modal.msgError('请完善必填信息')
        }
      })
    },
    /** 打开编辑抽屉 */
    handleEdit(row) {
      this.editDrawerVisible = true
      this.editLoading = true
      
      // 获取看板详情
      getKanbanOrder(row.id).then(response => {
        const data = response.data
        this.editForm = {
          id: data.id,
          kanbanCode: data.kanbanCode,
          frameworkId: data.frameworkId,
          frameworkCode: data.frameworkCode,
          receiverCompanyName: data.receiverCompanyName,
          receiverContact: data.receiverContact,
          receiverPhone: data.receiverPhone,
          senderCompanyName: data.senderCompanyName,
          senderContact: data.senderContact,
          senderPhone: data.senderPhone,
          materialCode: data.materialCode,
          materialName: data.materialName,
          materialUnit: data.materialUnit,
          packageType: data.packageType,
          packageCapacity: data.packageCapacity,
          requiredQty: data.requiredQty,
          unitPrice: data.unitPrice,
          taxRate: data.taxRate,
          totalPrice: data.totalPrice,
          requiredDeliveryTime: data.requiredDeliveryTime,
          plannedDeliveryTime: data.plannedDeliveryTime,
          remark: data.remark
        }
        
        // 更新协议信息显示
        this.handleEditFrameworkChange(data.frameworkId)
      }).catch(error => {
        console.error('获取看板详情失败:', error)
        this.$modal.msgError('获取看板详情失败')
        this.editDrawerVisible = false
      }).finally(() => {
        this.editLoading = false
      })
    },
    /** 关闭编辑抽屉 */
    handleEditCancel() {
      this.editDrawerVisible = false
      this.resetEditForm()
    },
    /** 重置编辑表单 */
    resetEditForm() {
      this.editForm = {
        id: null,
        kanbanCode: '',
        frameworkId: null,
        frameworkCode: '',
        receiverCompanyName: '',
        receiverContact: '',
        receiverPhone: '',
        senderCompanyName: '',
        senderContact: '',
        senderPhone: '',
        materialCode: '',
        materialName: '',
        materialUnit: '',
        packageType: '',
        packageCapacity: null,
        requiredQty: null,
        unitPrice: null,
        taxRate: null,
        totalPrice: null,
        requiredDeliveryTime: '',
        plannedDeliveryTime: '',
        remark: ''
      }
      if (this.$refs.editForm) {
        this.$refs.editForm.clearValidate()
      }
    },
    /** 编辑表单协议变化处理 */
    handleEditFrameworkChange(frameworkId) {
      const framework = this.frameworkOptions.find(item => item.id === frameworkId)
      if (framework) {
        this.editForm.frameworkCode = framework.frameworkCode
        this.editForm.receiverCompanyName = framework.receiverCompanyName
        this.editForm.receiverContact = framework.receiverContact
        this.editForm.receiverPhone = framework.receiverPhone
        this.editForm.senderCompanyName = framework.senderCompanyName
        this.editForm.senderContact = framework.senderContact
        this.editForm.senderPhone = framework.senderPhone
      }
    },
    /** 编辑表单物料变化处理 */
    handleEditMaterialChange(materialCode) {
      const material = this.materialOptions.find(item => item.code === materialCode)
      if (material) {
        this.editForm.materialName = material.name
        this.editForm.materialUnit = material.unit
        this.editForm.unitPrice = material.price
        // 重新计算总价
        this.calculateEditTotalPrice()
      } else {
        this.editForm.materialName = ''
        this.editForm.materialUnit = ''
        this.editForm.unitPrice = null
      }
    },
    /** 计算编辑表单总价 */
    calculateEditTotalPrice() {
      if (this.editForm.requiredQty && this.editForm.unitPrice && this.editForm.taxRate !== null) {
        const subtotal = this.editForm.requiredQty * this.editForm.unitPrice
        const tax = subtotal * (this.editForm.taxRate / 100)
        const total = subtotal + tax
        this.editForm.totalPrice = total.toFixed(2)
      } else {
        this.editForm.totalPrice = '0.00'
      }
    },
    /** 计算编辑表单计划发货时间 */
    calculateEditPlannedDeliveryTime() {
      if (this.editForm.requiredDeliveryTime) {
        // 默认提前1天发货
        const deliveryDate = new Date(this.editForm.requiredDeliveryTime)
        deliveryDate.setDate(deliveryDate.getDate() - 1)
        
        // 检查是否为周末，如果是则继续提前
        while (deliveryDate.getDay() === 0 || deliveryDate.getDay() === 6) {
          deliveryDate.setDate(deliveryDate.getDate() - 1)
        }
        
        // 格式化为字符串
        const year = deliveryDate.getFullYear()
        const month = String(deliveryDate.getMonth() + 1).padStart(2, '0')
        const day = String(deliveryDate.getDate()).padStart(2, '0')
        const hours = String(deliveryDate.getHours()).padStart(2, '0')
        const minutes = String(deliveryDate.getMinutes()).padStart(2, '0')
        const seconds = String(deliveryDate.getSeconds()).padStart(2, '0')
        
        this.editForm.plannedDeliveryTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
      } else {
        this.editForm.plannedDeliveryTime = ''
      }
    },
    /** 编辑保存草稿 */
    handleEditSaveDraft() {
      this.$refs.editForm.validate((valid) => {
        if (valid) {
          this.editSaveLoading = true
          // 准备提交数据
          const formData = { 
            ...this.editForm, 
            businessStatus: 10, // 10表示草稿状态（字典值）
            totalPrice: this.editTotalPriceDisplay
          }
          
          updateKanbanOrder(formData).then(response => {
            this.$modal.msgSuccess('保存草稿成功')
            this.editDrawerVisible = false
            this.resetEditForm()
            this.getList()
          }).catch(error => {
            console.error('保存草稿失败:', error)
            this.$modal.msgError('保存草稿失败，请重试')
          }).finally(() => {
            this.editSaveLoading = false
          })
        } else {
          this.$modal.msgError('请完善必填信息')
        }
      })
    },
    /** 编辑提交看板 */
    handleEditSubmit() {
      this.$refs.editForm.validate((valid) => {
        if (valid) {
          // 额外验证必要字段
          if (!this.editForm.frameworkId) {
            this.$modal.msgError('请选择供货协议')
            return
          }
          if (!this.editForm.materialCode) {
            this.$modal.msgError('请选择物料')
            return
          }
          if (!this.editForm.requiredQty || this.editForm.requiredQty <= 0) {
            this.$modal.msgError('请输入正确的需求数量')
            return
          }
          if (!this.editForm.requiredDeliveryTime) {
            this.$modal.msgError('请选择要求到货时间')
            return
          }
          
          this.editSubmitLoading = true
          // 准备提交数据
          const formData = { 
            ...this.editForm, 
            businessStatus: 20, // 20表示已创建状态
            totalPrice: this.editTotalPriceDisplay
          }
          
          updateKanbanOrder(formData).then(response => {
            this.$modal.msgSuccess('确认创建看板成功')
            this.editDrawerVisible = false
            this.resetEditForm()
            this.getList()
          }).catch(error => {
            console.error('确认创建看板失败:', error)
            this.$modal.msgError('确认创建看板失败，请重试')
          }).finally(() => {
            this.editSubmitLoading = false
          })
        } else {
          this.$modal.msgError('请完善必填信息')
        }
      })
    },
  },
  computed: {
    /** 含税总价显示 */
    totalPriceDisplay: {
      get() {
        if (this.addForm.requiredQty && this.addForm.unitPrice && this.addForm.taxRate !== null) {
          const subtotal = this.addForm.requiredQty * this.addForm.unitPrice
          const tax = subtotal * (this.addForm.taxRate / 100)
          const total = subtotal + tax
          return total.toFixed(2)
        }
        return '0.00'
      },
      set(value) {
        // 只读属性，不需要setter
      }
    }
  }
}
</script>

<style scoped>
.print-options {
  text-align: center;
  padding: 20px 0;
}

.print-options .el-button {
  margin: 0 10px;
  width: 120px;
}

/* 新增看板抽屉样式 */
.drawer-content {
  padding: 20px;
  height: 100%;
  overflow-y: auto;
}

/* 查看抽屉专用样式 */
.status-progress-card {
  margin-bottom: 20px;
}

.status-progress-card .section-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.status-progress-card .section-header i {
  margin-right: 8px;
  color: #409eff;
}

.status-progress-card .status-tag {
  margin-left: 10px;
}

.info-card, .material-card, .time-card, .status-card, .remark-card {
  margin-bottom: 20px;
}

.info-item {
  margin-bottom: 12px;
  display: flex;
  align-items: center;
}

.info-item label {
  font-weight: 600;
  color: #606266;
  min-width: 120px;
  margin-right: 8px;
}

.info-item span {
  color: #303133;
  flex: 1;
}

.remark-content {
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
  color: #606266;
  line-height: 1.6;
}

.form-section {
  margin-bottom: 20px;
}

.section-header {
  display: flex;
  align-items: center;
  font-weight: bold;
  color: #303133;
}

.section-header i {
  margin-right: 8px;
  color: #409EFF;
}

.framework-info {
  margin-top: 15px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.drawer-footer {
  position: sticky;
  bottom: 0;
  background: #fff;
  padding: 20px 0;
  text-align: right;
  border-top: 1px solid #e4e7ed;
  margin-top: 20px;
}

.drawer-footer .el-button {
  margin-left: 10px;
}

/* 表单样式优化 */
.el-form-item {
  margin-bottom: 18px;
}

.el-card {
  border: 1px solid #e4e7ed;
}

.el-card .el-card__header {
  background-color: #fafafa;
  border-bottom: 1px solid #e4e7ed;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .drawer-content {
    padding: 10px;
  }
  
  .el-col {
    margin-bottom: 10px;
  }
  
  .info-item {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .info-item label {
    min-width: auto;
    margin-bottom: 4px;
  }
}

/* 移动端优化 */
@media (max-width: 768px) {
  .drawer-content {
    padding: 15px;
  }
  
  .form-section {
    margin-bottom: 15px;
  }
  
  .drawer-footer {
    padding: 15px;
    flex-direction: column;
  }
  
  .drawer-footer .el-button {
    width: 100%;
    margin: 5px 0;
  }
  
  .section-header {
    font-size: 14px;
  }
  
  .el-form-item__label {
    font-size: 13px;
  }
}

/* 平板端优化 */
@media (min-width: 769px) and (max-width: 1199px) {
  .drawer-content {
    padding: 18px;
  }
  
  .drawer-footer .el-button {
    margin: 0 8px;
  }
}

/* 供货协议选择弹窗样式 */
.framework-dialog-content {
  max-height: 600px;
  overflow-y: auto;
}

.framework-dialog-content .demo-form-inline {
  background-color: #f5f7fa;
  padding: 15px;
  border-radius: 4px;
  margin-bottom: 20px;
}

.framework-dialog-content .el-table {
  border: 1px solid #e4e7ed;
}

.framework-dialog-content .el-table .current-row {
  background-color: #ecf5ff !important;
}

.framework-dialog-content .el-table .current-row td {
  background-color: #ecf5ff !important;
}
</style>